{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# Improving Performance using Cython"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "\n",
    "def arma(parameters, data, p=0, q=0):\n",
    "    tau = data.shape[0]\n",
    "    errors = np.zeros(tau)\n",
    "\n",
    "    for t in range(p, tau):\n",
    "        errors[t] = data[t] - parameters[0]\n",
    "        for i in range(p):\n",
    "            errors[t] -= parameters[i + 1] * data[t - i - 1]\n",
    "        for i in range(q):\n",
    "            if (t - i) >= 0:\n",
    "                # If not, lagged error is assumed to be 0\n",
    "                errors[t] -= parameters[i + p + 1] * errors[t - i - 1]\n",
    "\n",
    "    return np.asarray(errors)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "data = np.random.standard_normal(1000)\n",
    "parameters = np.array([1, 0.1, 0.1, 0.4, -0.8])\n",
    "p = 2\n",
    "q = 2\n",
    "errors = arma(parameters, data, p, q)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "%timeit arma(parameters, data, p, q)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Using Cython\n",
    "\n",
    "To run the code in the next cell, you need to have run\n",
    "\n",
    "```\n",
    "python setup_cython_arma.py build_ext -i\n",
    "```\n",
    "\n",
    "in the directory of this file.\n",
    "\n",
    "The Cythonized version should run around 500 times faster."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import cython_arma\n",
    "\n",
    "%timeit cython_arma.arma(parameters, data, p, q)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
